# -*- coding: utf-8 -*-
# @Author  : caiweichao
# @explain : 钉钉机器人通知

from Commons.operation_file.operation_ymal import ReadYaml
from Commons.basic_request.http_request import HttpRequset
from ConfigFile.contants_file import DING_CONFIG,YAML_FILE
from Commons.ui_auto.get_allure_data import CaseCount

import time
import hmac
import hashlib
import base64
import urllib.parse


class DingRobot:
    # 方法初始化的时候读取指定的机器人
    def __init__(self, robot_name):
        account = ReadYaml(file_url=YAML_FILE).get_every_config("Config")
        robotDetail = ReadYaml(file_url=DING_CONFIG).get_every_config(key=robot_name)

        try:
            if robotDetail.get("secret"):
                timestamp = str(round(time.time() * 1000))
                secret = str(robotDetail.get("secret"))
                secret_enc = secret.encode('utf-8')
                string_to_sign = '{}\n{}'.format(timestamp, secret)
                string_to_sign_enc = string_to_sign.encode('utf-8')
                hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
                sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
                self.res_url = robotDetail.get('url') + f"&timestamp={timestamp}&sign={sign}"
            else:
                self.res_url = robotDetail.get("url")
            self.header = {"Content-Type": "application/json", "Charset": "UTF-8"}

        except KeyError:
            raise KeyError(f'值{robot_name}错误请与配置文件核对')
        except Exception:
            raise Exception('未知异常请检查')

    # 对指定的机器人发起请求
    def res_dingding(self, type=None, title="线上监控", error_msg=None, msg=None, is_at=None):
        if type == 'markdown':
            msg_ding = {
                "msgtype": "markdown",
                "markdown": {
                    "title": title,
                    "text": msg
                },
                "at": {
                    "atMobiles": f"[{is_at}]"
                }
            }
        else:
            if error_msg:
                msg_ding = {
                    "msgtype": "text",
                    "text": {"content": f'【{title}】:\n{error_msg}\n{msg}'},
                    "at": {
                        "atMobiles": f"[{is_at}]"
                    }
                }
            else:
                msg_ding = {
                    "msgtype": "text",
                    "text": {"content": f'{title}:{msg}'},
                    "at": {
                        "atMobiles": f"[{is_at}]"
                    }
                }

        res = HttpRequset(method='post', url=self.res_url, data=msg_ding, headers=self.header)
        print(res.get_json())

    def res_allure_report(self, name, report_url, username, pwd, ):
        caseCount = CaseCount()
        failedCount = caseCount.failedCount() if caseCount.failedCount() == 0 else f"<font color=\"#FF0000\">{caseCount.failedCount()}</font>"
        brokenCount = caseCount.brokenCount() if caseCount.brokenCount() == 0 else f"<font color=\"#FFFF00\">{caseCount.brokenCount()}</font>"
        skippedCount = caseCount.skippedCount() if caseCount.skippedCount() == 0 else f"<font color=\"#CFCFCF\">{caseCount.skippedCount()}</font>"
        test_detail = {
            "msgtype": "markdown",
            "markdown": {
                "title": "测试报告明细",
                "text": f"### 测试结果明细:\n\n"
                        f"- 本次**测试用例**运行总数: {caseCount.totalCount()}\n\n"
                        f"- 用例通过率: {caseCount.passRate()}%\n\n"
                        f"- 通过case:<font color=\"#009900\">{caseCount.passCount()}</font>\n\n"
                        f"- 失败case:{failedCount}\n\n"
                        f"- 运行异常case:{brokenCount}\n\n"
                        f"- 跳过执行case:{skippedCount}\n\n"
            },
        }
        msg_ding = {
            "msgtype": "link",
            "link": {
                "text": f"点击查看详细报告:登录账号密码：{username}/{pwd}",
                "title": f"【{name}自动化日常巡检完成】",
                "picUrl": "",
                "messageUrl": report_url

            }
        }
        HttpRequset(method='post', url=self.res_url, data=test_detail, headers=self.header)
        HttpRequset(method='post', url=self.res_url, data=msg_ding, headers=self.header)